<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称" prop="lawFirmName">
              <el-input v-model="queryParams.lawFirmName" placeholder="请输入名称" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="擅长" prop="special">
              <el-input v-model="queryParams.special" placeholder="请输入擅长" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="类型" prop="lawFirmType">
              <el-select v-model="queryParams.lawFirmType" placeholder="请选择类型" clearable>
                <el-option value="1" label="律师"></el-option>
                <el-option value="2" label="律所"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lawyer:lawFirm:add']">新增</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['lawyer:lawFirm:edit']">修改</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['lawyer:lawFirm:remove']">删除</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="lawFirmList" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="律所ID" align="center" prop="lawFirmId" v-if="false"/>
        <el-table-column label="类型" align="center" prop="lawFirmType" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.lawFirmType === '1'">律师</el-tag>
            <el-tag type="warning" v-else>律所</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center" prop="lawFirmLogo" width="140">
          <template #default="scope">
            <image-preview :src="scope.row.lawFirmLogo" :width="59" :height="59"/>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="lawFirmName" width="200"/>
        <el-table-column label="联系电话" align="center" prop="contactPhone" width="160"/>
        <el-table-column label="擅长" align="center" prop="special"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="指派该律师" placement="top">
              <el-button link type="primary" icon="CircleCheck" @click="handleAssign(scope.row)" ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改律所信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="lawFirmFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="律所名称" prop="lawFirmName">
          <el-input v-model="form.lawFirmName" placeholder="请输入律所名称"/>
        </el-form-item>
        <el-form-item label="律所logo" prop="lawFirmLogo">
          <el-input v-model="form.lawFirmLogo" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="律所简介" prop="lawFirmDesc">
          <el-input v-model="form.lawFirmDesc" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="律所地址" prop="lawFirmAddress">
          <el-input v-model="form.lawFirmAddress" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="license">
          <el-input v-model="form.license" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入社会信用代码"/>
        </el-form-item>
        <el-form-item label="公司地址" prop="companyAddress">
          <el-input v-model="form.companyAddress" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="是否企业认证 0未认证，1已认证" prop="companyAuth">
          <el-input v-model="form.companyAuth" placeholder="请输入是否企业认证 0未认证，1已认证"/>
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-input v-model="form.province" placeholder="请输入省"/>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="form.city" placeholder="请输入市"/>
        </el-form-item>
        <el-form-item label="区" prop="district">
          <el-input v-model="form.district" placeholder="请输入区"/>
        </el-form-item>
        <el-form-item label="综合评分" prop="rating">
          <el-input v-model="form.rating" placeholder="请输入综合评分"/>
        </el-form-item>
        <el-form-item label="管理员ID" prop="adminUserId">
          <el-input v-model="form.adminUserId" placeholder="请输入管理员ID"/>
        </el-form-item>
        <el-form-item label="推荐首页(0不推荐，1推荐）" prop="curated">
          <el-input v-model="form.curated" placeholder="请输入推荐首页(0不推荐，1推荐）"/>
        </el-form-item>
        <el-form-item label="粉丝数量" prop="followers">
          <el-input v-model="form.followers" placeholder="请输入粉丝数量"/>
        </el-form-item>
        <el-form-item label="擅长" prop="special">
          <el-input v-model="form.special" placeholder="请输入擅长"/>
        </el-form-item>
        <el-form-item label="资格认证" prop="certification">
          <el-input v-model="form.certification" placeholder="请输入资格认证"/>
        </el-form-item>
        <el-form-item label="执业开始时间" prop="yearServiceTime">
          <el-date-picker clearable
                          v-model="form.yearServiceTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择执业开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Process" lang="ts">
import {listLawFirm, getLawFirm, delLawFirm, addLawFirm, updateLawFirm} from '@/api/lawfirm/lawfirm';
import {LawFirmVo, LawFirmQuery, LawFirmForm} from '@/api/lawfirm/lawfirm/types';
import {assignOrder, getSpuOrder} from '@/api/trade/order';
import {SpuOrderVo} from '@/api/trade/order/types';
import {RouteLocationNormalized} from 'vue-router';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const lawFirmList = ref<LawFirmVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const defaultSpuOrderVo = ref<SpuOrderVo>();
const defaultOrderId = ref('');
const queryFormRef = ref<ElFormInstance>();
const lawFirmFormRef = ref<ElFormInstance>();
const route = useRoute();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: LawFirmForm = {
  lawFirmId: undefined,
  lawFirmName: undefined,
  lawFirmLogo: undefined,
  lawFirmType: undefined,
  status: '0',
  lawFirmDesc: undefined,
  lawFirmAddress: undefined,
  companyName: undefined,
  license: undefined,
  creditCode: undefined,
  companyAddress: undefined,
  companyAuth: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  rating: undefined,
  adminUserId: undefined,
  curated: undefined,
  followers: undefined,
  special: undefined,
  certification: undefined,
  yearServiceTime: undefined,
  contactPhone: undefined
}
const data = reactive<PageData<LawFirmForm, LawFirmQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    lawFirmName: undefined,
    lawFirmLogo: undefined,
    lawFirmType: undefined,
    status: undefined,
    lawFirmDesc: undefined,
    lawFirmAddress: undefined,
    companyName: undefined,
    license: undefined,
    creditCode: undefined,
    companyAddress: undefined,
    companyAuth: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    rating: undefined,
    adminUserId: undefined,
    curated: undefined,
    followers: undefined,
    special: undefined,
    certification: undefined,
    yearServiceTime: undefined,
    contactPhone: undefined,
    params: {}
  },
  rules: {
    lawFirmId: [
      {required: true, message: "律所ID不能为空", trigger: "blur"}
    ],
    lawFirmName: [
      {required: true, message: "律所名称不能为空", trigger: "blur"}
    ],
    lawFirmLogo: [
      {required: true, message: "律所logo不能为空", trigger: "blur"}
    ],
    lawFirmType: [
      {required: true, message: "律所类型不能为空", trigger: "change"}
    ],
    status: [
      {required: true, message: "律所状态不能为空", trigger: "change"}
    ],
    lawFirmDesc: [
      {required: true, message: "律所简介不能为空", trigger: "blur"}
    ],
    lawFirmAddress: [
      {required: true, message: "律所地址不能为空", trigger: "blur"}
    ],
    companyName: [
      {required: true, message: "企业名称不能为空", trigger: "blur"}
    ],
    license: [
      {required: true, message: "营业执照不能为空", trigger: "blur"}
    ],
    creditCode: [
      {required: true, message: "社会信用代码不能为空", trigger: "blur"}
    ],
    companyAddress: [
      {required: true, message: "公司地址不能为空", trigger: "blur"}
    ],
    companyAuth: [
      {required: true, message: "是否企业认证 0未认证，1已认证不能为空", trigger: "blur"}
    ],
    province: [
      {required: true, message: "省不能为空", trigger: "blur"}
    ],
    city: [
      {required: true, message: "市不能为空", trigger: "blur"}
    ],
    district: [
      {required: true, message: "区不能为空", trigger: "blur"}
    ],
    rating: [
      {required: true, message: "综合评分不能为空", trigger: "blur"}
    ],
    adminUserId: [
      {required: true, message: "管理员ID不能为空", trigger: "blur"}
    ],
    curated: [
      {required: true, message: "推荐首页(0不推荐，1推荐）不能为空", trigger: "blur"}
    ],
    followers: [
      {required: true, message: "粉丝数量不能为空", trigger: "blur"}
    ],
    special: [
      {required: true, message: "擅长不能为空", trigger: "blur"}
    ],
    certification: [
      {required: true, message: "资格认证不能为空", trigger: "blur"}
    ],
    yearServiceTime: [
      {required: true, message: "执业开始时间不能为空", trigger: "blur"}
    ],
    contactPhone: [
      {required: true, message: "联系电话不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询律所信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLawFirm(queryParams.value);
  lawFirmList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  lawFirmFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: LawFirmVo[]) => {
  ids.value = selection.map(item => item.lawFirmId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加律所信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: LawFirmVo) => {
  reset();
  const _lawFirmId = row?.lawFirmId || ids.value[0];
  const res = await getLawFirm(_lawFirmId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改律所信息';
}

/** 提交按钮 */
const submitForm = () => {
  lawFirmFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.lawFirmId) {
        await updateLawFirm(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addLawFirm(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: LawFirmVo) => {
  const _lawFirmIds = row?.lawFirmId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delLawFirm(_lawFirmIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleAssign = async (row?: LawFirmVo) => {
  const _lawFirmId = row?.lawFirmId || ids.value[0];
  await proxy?.$modal.confirm(`是否确认指派${row.lawFirmName}处理该订单？`).finally(() => loading.value = false);
  await assignOrder(defaultOrderId.value, _lawFirmId);
  proxy?.$modal.msgSuccess('操作成功');
  handleClose();
};

const loadSpuOrder = async (orderId: string) => {
  defaultOrderId.value = orderId;
  await getDefaultOrder(orderId);
  await getList();
};

const getDefaultOrder = async (orderId: string) => {
  const res = await getSpuOrder(orderId);
  defaultSpuOrderVo.value = res.data;
};

const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: '{"action":"refresh"}',
    redirectedFrom: undefined,
    path: '/trade/Order'
  };
  proxy?.$tab.closeOpenPage(obj);
};

onMounted(() => {
  loadSpuOrder(route.params && (route.params.orderId as string));
});
</script>
